<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1, minimum-scale=1, user-scalable=no,maximum-scale=1">
    <title>WebSocket</title>
</head>
<body>


<script>

    let socket;
    let reconnectInterval = 1000; // 初始重连时间间隔，单位毫秒
    let maxReconnectAttempts = 5; // 最大重连次数
    let reconnectAttempts = 0; // 当前重连次数
    let reconnecting = false; // 标志是否正在尝试重连
    let loginStatus = false

    function connectWebSocket() {
        reconnecting = true
        socket = new WebSocket("ws://127.0.0.1:11234");

        socket.onopen = function (res) {
            loginStatus = true
            reconnecting = false; // 重置重连状态
            console.log("连接成功");
            reconnectAttempts = 0; // 重置重连计数
            socket.send('tom');
            let timer = setInterval(function () {
                if(loginStatus === false) {
                    console.log("清除定时器!")
                    clearInterval(timer)
                }
                socket.send('tom ' + (new Date()).getTime().toString());
            },1000)
        }

        socket.onclose = function (e) {
            loginStatus = false
            reconnecting = false
            console.log("WebSocket closed");
            if (reconnectAttempts < maxReconnectAttempts) {
                attemptReconnect();
            }
        }

        socket.onerror = function (err) {
            console.log("WebSocket error")
        }

        socket.onmessage = function(e) {
            if(e.data !== "1") {
                console.log("收到服务端的消息：" + e.data);
            }

        };
    }

    function attemptReconnect() {
        if (reconnecting) return;
        reconnecting = true;
        console.log("正在重连...")
        setTimeout(() => {
            reconnectAttempts++;
            // reconnectInterval *= 2; // 使用指数退避算法，加倍重连时间间隔
            // console.log(`Attempting to reconnect (${reconnectAttempts}/${maxReconnectAttempts})...`);
            connectWebSocket();
        }, reconnectInterval);
    }

    // 启动 WebSocket 连接
    connectWebSocket();
</script>
</body>
</html>